package org.linlinjava.litemall.admin.service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import org.apache.shiro.SecurityUtils;
import org.linlinjava.litemall.admin.beans.dto.ShopCheckDto;
import org.linlinjava.litemall.admin.beans.dto.ShopCheckItemDto;
import org.linlinjava.litemall.admin.beans.enums.PromptEnum;
import org.linlinjava.litemall.admin.beans.vo.ShopCheckVo;
import org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants;
import org.linlinjava.litemall.admin.util.DateUtil;
import org.linlinjava.litemall.admin.util.RandomUtils;
import org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallMerchandise;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallShopCheck;
import org.linlinjava.litemall.db.domain.LitemallShopCheckItem;
import org.linlinjava.litemall.db.domain.LitemallShopCheckItemVo;
import org.linlinjava.litemall.db.domain.LitemallShopMerchandise;
import org.linlinjava.litemall.db.service.LitemallMerchandiseService;
import org.linlinjava.litemall.db.service.LitemallShopCheckItemService;
import org.linlinjava.litemall.db.service.LitemallShopCheckService;
import org.linlinjava.litemall.db.service.LitemallShopMerchandiseService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 店检查服务
 * 门店服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Service
public class ShopCheckService {
    /**
     * litemall店服务
     */
    @Autowired
	private LitemallShopService litemallShopService;
    /**
     * litemall商店商品服务
     */
    @Autowired
	private LitemallShopMerchandiseService litemallShopMerchandiseService;
    /**
     * litemall商品服务
     */
    @Autowired
	private LitemallMerchandiseService litemallMerchandiseService;
    /**
     * litemall商店检查服务
     */
    @Autowired
    private LitemallShopCheckService litemallShopCheckService;
    /**
     * litemall商店检查项目服务
     */
    @Autowired
    private LitemallShopCheckItemService litemallShopCheckItemService;

    /**
     * 列表
     *
     * @param shopId    商店id
     * @param checkNo   检查没有
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param page      页面
     * @param limit     限制
     * @param sort      排序
     * @param order     订单
     * @return {@link Object}
     */
    public Object list(Integer shopId, String checkNo, String startDate, String endDate,String shopName, Integer page, Integer limit, String sort, String order){
    	DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    	LocalDateTime startTimes = null;
    	LocalDateTime endTimes = null;
    	if(StrUtil.isNotEmpty(startDate)&&StrUtil.isNotEmpty(endDate)){
    		startTimes = LocalDate.parse(startDate, timeDtf).atTime(LocalTime.MIN);
			endTimes = LocalDate.parse(endDate, timeDtf).atTime(LocalTime.MAX);
    	}
    	List<LitemallShopCheck> result = litemallShopCheckService.querySelective(shopId, checkNo, startTimes, endTimes,shopName, page, limit, sort, order);
        return ResponseUtil.okList(result);
    }

    /**
     * 读
     *
     * @param id id
     * @return {@link Object}
     */
    public Object read(Integer id){
    	if(null == id) {
    		return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
    	}

    	LitemallShopCheck litemallShopCheck = litemallShopCheckService.findById(id);
    	List<LitemallShopCheckItemVo> litemallShopCheckItems = litemallShopCheckItemService.queryByShopCheckId(id);
    	ShopCheckVo shopCheckVo = new ShopCheckVo();
    	shopCheckVo.setCheck(litemallShopCheck);
    	shopCheckVo.setCheckItems(litemallShopCheckItems);
    	return ResponseUtil.ok(shopCheckVo);
    }

    /**
     * 创建
     *
     * @param shopCheckDto 店检查dto
     * @return {@link Object}
     */
    @Transactional(rollbackFor = Exception.class)
    public Object create(ShopCheckDto shopCheckDto){
    	if(null == shopCheckDto.getItems()) {
    		return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
    	}
		if(shopCheckDto.getShopId()==null){
			throw ServiceExceptionUtil.exception(ErrorCodeConstants.LUMIERE_SHOP_ID_IS_NULL);
		}


    	Integer shopId = shopCheckDto.getShopId();
    	LitemallShop litemallShop = litemallShopService.getInfoById(shopId);

    	//保存盘点信息
    	LitemallShopCheck litemallShopCheck = new LitemallShopCheck();
    	litemallShopCheck.setShopId(shopId);
    	litemallShopCheck.setShopName(litemallShop.getName());
    	litemallShopCheck.setCheckNo(genCheckNo());
    	litemallShopCheck.setCheckTime(LocalDateTime.now());
    	LitemallAdmin admin = (LitemallAdmin)SecurityUtils.getSubject().getPrincipal();
    	Integer userId = admin.getId();
    	litemallShopCheck.setCheckUserId(userId);
    	litemallShopCheck.setCheckUserName(admin.getNickName());
    	litemallShopCheck.setAddUserId(userId);
    	litemallShopCheckService.create(litemallShopCheck);

    	//保存盘点项
    	List<ShopCheckItemDto> items = shopCheckDto.getItems();
    	if(null != items) {
    		Integer shopCheckId = litemallShopCheck.getId();
    		for (ShopCheckItemDto shopCheckItemDto : items) {
    			LitemallShopCheckItem shopCheckItem = new LitemallShopCheckItem();
    			shopCheckItem.setShopCheckId(shopCheckId);
    			//获取商品货品id
    			Integer shopMerchandiseId = shopCheckItemDto.getShopMerchandiseId();
    			shopCheckItem.setShopMerchandiseId(shopMerchandiseId);
    			shopCheckItem.setSystemSurplusNumber(shopCheckItemDto.getSystemSurplusNumber());
				Double checkNumber = shopCheckItemDto.getCheckNumber().doubleValue();
    			shopCheckItem.setCheckNumber(checkNumber);
    			Integer lossNumber = shopCheckItemDto.getLossNumber();
    			shopCheckItem.setLossNumber(lossNumber);
    			shopCheckItem.setRemark(shopCheckItemDto.getRemark());
    			shopCheckItem.setAddUserId(userId);
    			litemallShopCheckItemService.create(shopCheckItem);

    			//如果库存有改的话，就修改商品原料库存
    			if(lossNumber != 0) {
    				//修改商品库存
    				LitemallShopMerchandise shopMerchandise = litemallShopMerchandiseService.findById(shopMerchandiseId);
    				LitemallMerchandise merchandise = litemallMerchandiseService.findById(shopMerchandise.getMerchandiseId());
    				shopMerchandise.setNumber(checkNumber);
					Double basicNumber = checkNumber*merchandise.getCheckRatio();//(盘点数量*盘点比例)
    				shopMerchandise.setBasicNumber(basicNumber);
    				litemallShopMerchandiseService.updateById(shopMerchandise);
    			}
    		}
    	}

    	return ResponseUtil.ok();
    }

    /**
     * 创检查没有
     * 生成盘点编号
     *
     * @return {@link String}
     */
    private String genCheckNo() {
    	return "SC"+ DateUtil.dateToString(LocalDateTime.now(), "yyyyMMddHHmmss") + RandomUtils.generateRandomStr(2);
    }

	public ResponseUtil.Response getShopAll() {
		return ResponseUtil.ok(litemallShopService.getShopAll());
	}
}
